import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from db_wish import Wish,FBUser

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')

    greetings = db.GqlQuery("SELECT * "
                            "FROM Wish ")

    for greeting in greetings:

      self.response.out.write('%s wrote:' % greeting.user.uid)
      self.response.out.write('<blockquote>%s</blockquote> time:%s<br />' %
                               (
                                  cgi.escape(greeting.word),
                                  greeting.created
                                )

                              )
    self.response.out.write("=================<br />")

    
    users = db.GqlQuery("SELECT * "
                            "FROM FBUser ")
    
    for user in users:
        self.response.out.write('%s wrote:<br/>' % user.uid)
        for wish in user.wishs:
            self.response.out.write('<br />%s' % wish.word)
    
    self.response.out.write("""
          <form action="/sign" method="post">
            <div><input type="text" name="uid" value="uid" /></div>
            <div><textarea name="word" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Sign Guestbook"></div>
          </form>
        </body>
      </html>""")


class Guestbook(webapp.RequestHandler):
  def post(self):

    
    uid = self.request.get('uid')
    #search same User obj first
    u = FBUser(uid=uid,key_name=uid)    
    u.put()

    word = self.request.get('word')
    greeting = Wish(user=u,
                    word=word)

    greeting.put()
    self.redirect('/')
    
class Clear(webapp.RequestHandler):
  def get(self):
    db.delete(FBUser.all())
    db.delete(Wish.all())
    self.response.out.write("ok")
    
    

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/sign', Guestbook),
  ('/cleardb',Clear)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()

